package tw.com.diray.set;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import tw.com.diary.ae.com.Msg;
import tw.com.diary.api.com.Contract;
import tw.com.diary.api.domain.UserInfoDTO;
import tw.com.diary.api.service.UserInfoService;
import tw.com.diary.core.UserInfoServiceImpl;
import tw.com.diray.R;
import tw.com.diray.comm.ui.DirToast;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.TimePicker;

/**
 * 個人資訊
 * 
 * @author Andy
 * 
 */
public class UserInfoFragment extends Fragment {

	private UserInfoDTO dto = null;
	private UserInfoService service = null;

	private TimePickerDialog dialog;

	private CheckBox isAlert;

	private TextView nickNam;
	private TextView email;
	private TextView alertTime;

	private final static int ALERT_CODE = 001;

	private AlertDialog accountDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		this.setHasOptionsMenu(true);

		this.dto = new UserInfoDTO();
		this.service = new UserInfoServiceImpl();

		AccountManager am = (AccountManager) getActivity().getSystemService(Context.ACCOUNT_SERVICE);

		final Account[] accounts = am.getAccounts();

		Builder builder = new Builder(getActivity());
		builder.setTitle("select acoounts");

		final CharSequence[] sequence = new String[10];

		List<String> seqs = new ArrayList<String>();
		for (Account account : accounts) {
			seqs.add(account.name);
		}

		builder.create();

		this.service.getSource(dto, this.getActivity());

		this.createTimeDialog();

	}

	/**
	 * 建立時間選擇視窗
	 */
	public void createTimeDialog() {
		this.dialog = new TimePickerDialog(this.getActivity(), new OnTimeSetListener() {

			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

				dto.setAlertContent(String.format("%02d:%02d", hourOfDay, minute));

				dto.setMiniute(String.format("%02d", hourOfDay));
				dto.setHour(String.format("%02d", minute));

				UserInfoFragment.this.alertTime.setText(dto.getAlertContent());

				// TODO Auto-generated method stub

			}
		}, 18, 00, true);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.frament_info_view, container, false);

		this.isAlert = (CheckBox) rootView.findViewById(R.id.isAlert);

		this.nickNam = (TextView) rootView.findViewById(R.id.nickName);

		this.email = (TextView) rootView.findViewById(R.id.email);

		this.alertTime = (TextView) rootView.findViewById(R.id.alerTime);

		this.nickNam.setText(dto.getNickName());
		this.email.setText(dto.getEmail());
		this.isAlert.setSelected(dto.isAlertFlag());
		this.alertTime.setText(dto.getAlertContent());

		this.isAlert.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				// TODO Auto-generated method stub

				if (isChecked) {
					dialog.show();
				}

			}
		});

		return rootView;
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub

		inflater.inflate(R.menu.user_info, menu);

		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		final int id = item.getItemId();

		switch (id) {
		case R.id.action_sumit:

			dto.setAlertContent(this.alertTime.getText().toString());
			dto.setAlertFlag(this.isAlert.isChecked());
			dto.setEmail(this.email.getText().toString());
			dto.setNickName(this.nickNam.getText().toString());

			service.saveProperty(dto, getActivity());

			if (dto.isAlertFlag()) {

				final long systemTime = System.currentTimeMillis();

				Calendar calendar = Calendar.getInstance();
				calendar.setTimeInMillis(System.currentTimeMillis());
				calendar.setTimeZone(TimeZone.getTimeZone("GMT+8"));
				// calendar.set(Calendar.HOUR, Integer.parseInt(dto.getHour()));
				// calendar.set(Calendar.MINUTE,
				// Integer.parseInt(dto.getMiniute()));
				calendar.add(Calendar.MINUTE, 1);

				long selectTime = calendar.getTimeInMillis();

				if (systemTime > selectTime) {
					DirToast.show(getActivity(), Msg.S0001, "系統時間大於修改時間");
					calendar.add(Calendar.DAY_OF_MONTH, 1);// 多加一天，表示明天再提醒
					selectTime = calendar.getTimeInMillis();
				}

				// 計算
				final long time = selectTime - systemTime;
				final Long firstTime = time + SystemClock.elapsedRealtime();// 開機時間＋差異時間＝＝提醒時間

				// =設定廣播
				Intent it = new Intent();

				it.setAction(Contract.Action.RECEICE_ACTION);
				it.addCategory(Intent.CATEGORY_DEFAULT);

				PendingIntent pendReciver = PendingIntent.getBroadcast(getActivity(), ALERT_CODE, it, PendingIntent.FLAG_ONE_SHOT);

				AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);

				am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, 24 * 60 * 60 * 1000, pendReciver);
			}

			break;
		case R.id.action_back:
			this.getActivity().finish();
			break;
		}

		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}

}
